﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Ria.ApplicationServices;
using CARE;
using CARE.Web;
using CARE.Web.Services;
using CARE.GraphProviderServiceReference;
using System.Xml.Linq;

namespace CARE
{
    public partial class GenerateSocialNetworkWindow : ChildWindow
    {
        private GraphProviderServiceClient gp;

        public IWizardButtonController wizardButtonController;

		private bool saveOnDisc = false; 

        int conditionValue;

        private List<String> parametersTypes;

        private String fileContent;

        SimulationParameters parameters;

        public GenerateSocialNetworkWindow(bool save)
        {
            InitializeComponent();

			saveOnDisc = save;

            fileContent = null;

            gp = new GraphProviderServiceClient();

            parameters = SimulationParameters.getInstance();

            gp.GetParametersFromMethodCompleted += new EventHandler<GetParametersFromMethodCompletedEventArgs>(gp_GetParametersFromMethodCompleted);
            gp.GetParametersTypesFromMethodCompleted += new EventHandler<GetParametersTypesFromMethodCompletedEventArgs>(gp_GetParametersTypesFromMethodCompleted);
            gp.GenerateGraphCompleted += new EventHandler<GenerateGraphCompletedEventArgs>(gp_GenerateGraphCompleted);
            gp.GetAvailableMethodsOfGeneratorCompleted += new EventHandler<GetAvailableMethodsOfGeneratorCompletedEventArgs>(gp_GetAvailableMethodsOfGeneratorCompleted);
            gp.GenerateGraphAndSaveGraphMLCompleted += new EventHandler<GenerateGraphAndSaveGraphMLCompletedEventArgs>(gp_GenerateGraphAndSaveGraphMLCompleted);
            gp.GetAvailableMethodsOfGeneratorAsync();
        }   

        void gp_GetAvailableMethodsOfGeneratorCompleted(object sender, GetAvailableMethodsOfGeneratorCompletedEventArgs e)
        {
            List<String> avlMethods = e.Result as List<String>;
            foreach (string item in avlMethods)
                generators.Items.Add(item);
            generators.IsEnabled = true;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void Generate_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (generators.SelectedItem != null)
            {
                string methodName = generators.SelectedItem.ToString();
                List<string> parameters = new List<string>();

                for (int i = 0; i < generatorsPanel.Children.Count; i++)
                    parameters.Add(((generatorsPanel.Children[i] as StackPanel).Children[0] as TextBox).Text);

                if (saveOnDisc)
                {
                    gp.GenerateGraphAndSaveGraphMLAsync(methodName, parameters, parametersTypes, conditionValue);                    
                }
                else
                {
                    gp.GenerateGraphAsync(methodName, parameters, parametersTypes, conditionValue);
                }
            }
        }

        void gp_GenerateGraphCompleted(object sender, GenerateGraphCompletedEventArgs e)
        {
            parameters.SocialNetworkGraph = e.Result;
            wizardButtonController.EnableNext();
            this.Close();
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog mySaveFileDialog = new SaveFileDialog();
            mySaveFileDialog.Filter = "XML Files (*.xml)|*.xml|GraphML Files (*.graphml)|*.graphml";
            mySaveFileDialog.FilterIndex = 1;
            if (fileContent != null)
            {
                bool? ret = mySaveFileDialog.ShowDialog();
                if (ret == true)
                {
                    using (Stream fs = (Stream)mySaveFileDialog.OpenFile())
                    {
                        byte[] content = (new UTF8Encoding(true)).GetBytes(fileContent);
                        fs.Write(content, 0, content.Length);
                        fs.Close();
                    }
                }
            }

            this.Close();
        }

        string GetParameterDescription(string method, string p)
        {
            Type res = typeof(CARE.Resources.ApplicationStrings);
            string description = (string)res.GetProperty(method + "_" + p, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static).GetValue(null, null);
            return description;
        }

        private void Generators_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (generators.SelectedItem != null)
            {
                string methodName = generators.SelectedItem.ToString();

                gp.GetParametersFromMethodAsync(methodName);
                gp.GetParametersTypesFromMethodAsync(methodName);                
            }
        }

        private void Condition_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
               conditionValue = Convert.ToInt32(
                   condition.Text.Length > 0 ?
                   condition.Text : "0"
               );
        }


        void gp_GetParametersFromMethodCompleted(object sender, GetParametersFromMethodCompletedEventArgs e)
        {
            var parameters = e.Result;
            generatorsPanel.Children.Clear();
            foreach (var p in parameters)
            {
                StackPanel sp = new StackPanel()
                {
                    Orientation = Orientation.Horizontal,
                    Margin = new Thickness(0, 10, 0, 0)
                };
                sp.Children.Add(new TextBox()
                {
                    Width = 100
                });
                sp.Children.Add(new TextBlock()
                {
                    Text = GetParameterDescription(generators.SelectedItem.ToString(), p)
                });

                generatorsPanel.Children.Add(sp);
            }
        }

        void gp_GetParametersTypesFromMethodCompleted(object sender, GetParametersTypesFromMethodCompletedEventArgs e)
        {
            parametersTypes = new List<String>();
            foreach (var item in e.Result)
                parametersTypes.Add(item);
        }

        void gp_GenerateGraphAndSaveGraphMLCompleted(object sender, GenerateGraphAndSaveGraphMLCompletedEventArgs e)
        {
            fileContent = e.Result;
            saveButton.Visibility = Visibility.Visible;
            generateButton.Visibility = Visibility.Collapsed;
        }
    }
}